import React, { useRef, useState, useEffect } from 'react';

// styles
import styles from './index.less';
// 自定义组件
// apis

export default () => {
  const DrawTool = useRef(null);
  const [menuList, setMenuList] = useState([
    { name: '点', key: 'point' },
    { name: '线', key: 'polyline' },
    { name: '圆', key: 'circle' },
    { name: '矩形', key: 'rect' },
    { name: '多边形', key: 'polygon' },
  ]);
  const [activeKey, setActiveKey] = useState('');

  const initDrawInstance = () => {
    DrawTool.current = new DX5S.MeasureTool(window?.LFTViewer); // 创建标绘实例
    console.log(DrawTool.current);
  };
  // 开始标绘
  const DrawMeasureFun = (key) => {
    clearMeasureLayer();
    if (activeKey === key) {
      setActiveKey('');
    } else {
      setActiveKey(key);
    }
    switch (key) {
      case 'circle':
        DrawTool.current.startDrawCircle((data) => {
          console.log('绘制完成了', data);
          setActiveKey(''); // 绘制完成后的回调
        });
        break;
      case 'polygon':
        DrawTool.current.startDrawPolygon((data) => {
          console.log('绘制完成了', data);
          setActiveKey(''); // 绘制完成后的回调
        });
        break;
      case 'rect':
        DrawTool.current.startDrawRectangle((data) => {
          console.log('绘制完成了', data);
          setActiveKey(''); // 绘制完成后的回调
        });
        break;
      case 'polyline':
        DrawTool.current.startDrawPolyline((data) => {
          console.log('绘制完成了', data);
          setActiveKey(''); // 绘制完成后的回调
        });
        break;
      default:
        break;
    }
  };

  const clearMeasureLayer = () => {
    setActiveKey('');
    let measureTool = DrawTool.current;
    if (measureTool) {
      measureTool?.remove();
    }
  };
  useEffect(() => {
    initDrawInstance();
    return () => {
      clearMeasureLayer();
    };
  }, []);
  return (
    <div className={styles.DrawContainer}>
      <div className="measure-box">
        {menuList.map((v) => {
          return (
            <div
              className={`measure-item ${
                activeKey === v.key ? 'measure-item-active' : ''
              }`}
              key={v.key}
              onClick={() => {
                setActiveKey(v.key);
                DrawMeasureFun(v.key);
              }}
            >
              {v.name}
            </div>
          );
        })}
        <div
          className="measure-item measure-item-del"
          onClick={clearMeasureLayer}
        >
          清除测距
        </div>
      </div>
    </div>
  );
};
